package com.yc.testupload.crawler.task;

import com.yc.testupload.crawler.config.WebsiteConfig;
import com.yc.testupload.crawler.config.ChannelConfig;
import com.yc.testupload.crawler.config.WebsiteConfigManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;

/**
 * 任务列表类
 * 管理所有的抓取任务，存储网站频道与文库分类的对应关系
 */
public class TaskList {
    private static final Logger logger = LogManager.getLogger(TaskList.class);
    private static TaskList instance;
    private List<CrawlTask> tasks;

    // 私有构造函数，实现单例模式
    private TaskList() {
        tasks = new ArrayList<>();
        // 初始化任务列表
        initTasks();
    }

    // 获取单例实例
    public static synchronized TaskList getInstance() {
        if (instance == null) {
            instance = new TaskList();
        }
        return instance;
    }

    /**
     * 初始化任务列表
     * 从WebsiteConfigManager中加载所有网站和频道的配置，创建任务
     */
    private void initTasks() {
        WebsiteConfigManager configManager = WebsiteConfigManager.getInstance();
        Map<String, WebsiteConfig> websiteConfigs = configManager.getAllWebsiteConfigs();

        if (websiteConfigs.isEmpty()) {
            logger.warn("没有找到任何网站配置，可能是配置文件加载失败");
        }

        for (Map.Entry<String, WebsiteConfig> entry : websiteConfigs.entrySet()) {
            String websiteId = entry.getKey();
            WebsiteConfig websiteConfig = entry.getValue();
            Map<String, ChannelConfig> channels = websiteConfig.getChannels();

            if (channels.isEmpty()) {
                logger.warn("网站 {} 没有配置任何频道", websiteConfig.getName());
                continue;
            }

            for (Map.Entry<String, ChannelConfig> channelEntry : channels.entrySet()) {
                String channelId = channelEntry.getKey();
                ChannelConfig channelConfig = channelEntry.getValue();

                // 创建抓取任务
                CrawlTask task = new CrawlTask(
                        websiteId,
                        websiteConfig.getName(),
                        websiteConfig.getDomain(),
                        channelId,
                        channelConfig.getName(),
                        channelConfig.getCategoryId(),
                        channelConfig.getRegexPatterns()
                );

                addTask(task);
                logger.info("已添加抓取任务: 网站={}, 频道={}, 分类ID={}", 
                        websiteConfig.getName(), 
                        channelConfig.getName(), 
                        channelConfig.getCategoryId());
            }
        }
        
        logger.info("任务列表初始化完成，共{}个任务", tasks.size());
    }

    /**
     * 添加任务
     */
    public void addTask(CrawlTask task) {
        tasks.add(task);
    }

    /**
     * 根据网站ID和频道ID获取任务
     */
    public CrawlTask getTask(String websiteId, String channelId) {
        for (CrawlTask task : tasks) {
            if (task.getWebsiteId().equals(websiteId) && task.getChannelId().equals(channelId)) {
                return task;
            }
        }
        return null;
    }

    /**
     * 根据URL获取对应的任务
     */
    public CrawlTask getTaskByUrl(String url) {
        WebsiteConfigManager configManager = WebsiteConfigManager.getInstance();
        WebsiteConfig websiteConfig = configManager.getWebsiteConfigByUrl(url);
        
        if (websiteConfig != null) {
            // 首先尝试精确匹配URL和频道的特定标识
            for (CrawlTask task : tasks) {
                if (task.getWebsiteName().equals(websiteConfig.getName())) {
                    // 特殊处理Java面试题频道
                    if (task.getChannelId().equals("java-interview") && 
                            (url.toLowerCase().contains("java") || url.toLowerCase().contains("spring") || 
                             url.toLowerCase().contains("hibernate") || url.toLowerCase().contains("mybatis"))) {
                        logger.info("URL匹配到Java面试题频道: {}", url);
                        return task;
                    }
                }
            }
            
            // 如果没有匹配到特殊频道，获取默认频道的任务
            for (CrawlTask task : tasks) {
                if (task.getWebsiteName().equals(websiteConfig.getName())) {
                    logger.info("URL匹配到默认频道: {}", url);
                    return task;
                }
            }
        }
        return null;
    }

    /**
     * 获取所有任务
     */
    public List<CrawlTask> getAllTasks() {
        return new ArrayList<>(tasks);
    }

    /**
     * 获取所有网站的任务分组
     */
    public Map<String, List<CrawlTask>> getTasksByWebsite() {
        Map<String, List<CrawlTask>> tasksByWebsite = new HashMap<>();
        
        for (CrawlTask task : tasks) {
            String websiteId = task.getWebsiteId();
            if (!tasksByWebsite.containsKey(websiteId)) {
                tasksByWebsite.put(websiteId, new ArrayList<>());
            }
            tasksByWebsite.get(websiteId).add(task);
        }
        
        return tasksByWebsite;
    }

    /**
     * 获取所有分类ID的映射关系
     */
    public Map<String, Integer> getCategoryMapping() {
        Map<String, Integer> categoryMapping = new HashMap<>();
        
        for (CrawlTask task : tasks) {
            String key = task.getWebsiteId() + ":" + task.getChannelId();
            categoryMapping.put(key, task.getCategoryId());
        }
        
        return categoryMapping;
    }

    /**
     * 根据网站ID和频道ID获取对应的分类ID
     */
    public Integer getCategoryId(String websiteId, String channelId) {
        CrawlTask task = getTask(websiteId, channelId);
        return task != null ? task.getCategoryId() : null;
    }

    /**
     * 重新加载任务列表
     */
    public void reloadTasks() {
        tasks.clear();
        initTasks();
        logger.info("已重新加载所有抓取任务，共{}个任务", tasks.size());
    }
}